package leetcode_1_200;

import node.Node;

import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.List;

public class LeeCode_116 {
    public static void main(String[] args) {
        Node node = new Node(1, new Node(2, new Node(4), new Node(5), null),
                new Node(3, new Node(6), new Node(7), null), null);
        connect(node);
    }
    private static Node connect(Node root) {
        if (root == null)
            return null;
        int depth = getDepth(root, 0);
        List<List<Node>> contains = new ArrayList<>(depth);
        for (int i = 0; i < depth; i++)
            contains.add(new ArrayList<>());
        f(contains, root, 0);
        for (int i = 0; i < contains.size(); i++) {
            List<Node> contain = contains.get(i);
            for (int j = 0; j < contain.size() - 1; j++) {
                contain.get(j).next = contain.get(j + 1);
            }
        }
        return root;
    }
    private static void f(List<List<Node>> contains, Node node, int depth){
        if (node == null)
            return;
        contains.get(depth).add(node);
        f(contains, node.left, depth + 1);
        f(contains, node.right, depth + 1);
    }
    private static int getDepth(Node node, int depth){
        if (node == null)
            return depth;
        return getDepth(node.left, depth + 1);
    }
}
